package com.txsj.scan.presenter;

import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;
import com.txsj.scan.base.BasePresenter;
import com.txsj.scan.bean.BaseListResult;
import com.txsj.scan.bean.BaseResult;
import com.txsj.scan.bean.EpcInfo;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.InventoryChangeBean;
import com.txsj.scan.bean.InventoryIdBean;
import com.txsj.scan.bean.WarehouseBean;
import com.txsj.scan.http.ApiServer;
import com.txsj.scan.http.requestframework.RetrofitManager;
import com.txsj.scan.utils.MD5Util;
import com.txsj.scan.utils.PreferenceUtil;
import com.txsj.scan.utils.Trace;
import com.txsj.scan.view.IInventoryView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @Created by WangChuangJun on 2018/11/13
 * @Describe
 */
public class InventoryPresenter extends BasePresenter<IInventoryView> {

    private static final int ON_ERROR = 0x110;
    private static final int ON_SUCCESS = 0x111;
    private static final int ON_LOADING = 0x112;

    private Thread cacheGoodsThread;    //缓存指定仓库商品列表
    private boolean isRunning;//判断当前线程的运行状态，true:正在运行， false:运行结束
    private int page;
    private String warehouse_id;
    private List<GoodsInfo> goodsList;

    public List<GoodsInfo> getGoodsList() {
        return goodsList;
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ON_ERROR:
                    if (null!=view)
                    view.onError("加载失败");
                    break;
                case ON_LOADING:
                    if (null!=view)
                    view.onLoading();
                    break;
                case ON_SUCCESS:
                    if (null!=view)
                    view.onSuccess("");
                    break;
            }
        }
    };

    public InventoryPresenter(IInventoryView view) {
        super(view);
    }

    @Override
    protected void initModel() {
        goodsList = new ArrayList<>();

    }

    /**
     * 根据批次信息和仓库id返回库存id,用于盘点提交
     *
     * @param list
     * @param warehouesId
     */
    public void getScanInventoryIdList(List<EpcInfo> list, String warehouesId) {
        if (list.size() == 0) return;
        Map<String, String> params = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID, ""));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getInt(PreferenceUtil.USER_ID, 0));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.TOKEN, ""));
        builder.append("|");
        builder.append(0);
        builder.append("|");
        params.put("brandtoken", builder.toString());
        params.put("warehouse_id", warehouesId);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i).getBatch_id());
            if (i < list.size() - 1) {
                sb.append(",");
            }
        }
        params.put("batch_ids", sb.toString());
        params.put("timeStamp", System.currentTimeMillis() / 1000 + "");//加时间戳参数
        params.put("sign", MD5Util.md5(params));//md5加密并加参数
        view.onLoading();
        RetrofitManager.getDefault().create(ApiServer.class).getInventoryIdList(RetrofitManager.getHeader(), params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseListResult<InventoryIdBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseListResult<InventoryIdBean> result) {
                        if (result.isSuccess()) {
                            if (null != result.getData() && result.getData().size() > 0) {
                                view.onInventoryIdSuccess(result.getData());
                            } else {
                                view.onInventoryIdEmpty("暂无数据");
                            }
                        } else {
                            view.onInventoryIdError("请重试");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.onInventoryIdError("网络异常");
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 提交盘点的批次
     *
     * @param changeList
     */
    public void getCommitChangeList(List<InventoryChangeBean> changeList, WarehouseBean warehouseBean, String remark) {
        Map<String, String> params = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID, ""));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getInt(PreferenceUtil.USER_ID, 0));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.TOKEN, ""));
        builder.append("|");
        builder.append(0);
        builder.append("|");
        params.put("brandtoken", builder.toString());
        params.put("bill_remark", remark);
        params.put("check_status", "2");
        params.put("employee_id", PreferenceUtil.getInstance().getInt(PreferenceUtil.USER_ID, 0) + "");
        params.put("employee_name", PreferenceUtil.getInstance().getString(PreferenceUtil.ROLE,""));
        String goods_json = new Gson().toJson(changeList);
        params.put("goods_json", goods_json);
        params.put("warehouse_id", warehouseBean.getWarehouse_id() + "");
        params.put("warehouse_name", warehouseBean.getWarehouse_name());
        params.put("timeStamp", System.currentTimeMillis() / 1000 + "");//加时间戳参数
        params.put("sign", MD5Util.md5(params));//md5加密并加参数
        view.onLoading();
        RetrofitManager.getDefault().create(ApiServer.class).commitInventoryChangeList(RetrofitManager.getHeader(), params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResult>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            view.onCommitSuccess();
                        } else {
                            view.onCommitError("提交失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.onCommitError("网络异常");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 根据商品条码获取商品数据
     *
     * @param code
     */
    public void fromCodeGetGoodsData(String code) {
        //6902538004052
        //4891028706656
        Map<String, String> params = new HashMap<>();
        params.put("userid", PreferenceUtil.getInstance().getInt(PreferenceUtil.USER_ID, 0) + "");
        params.put("token", PreferenceUtil.getInstance().getString(PreferenceUtil.TOKEN, ""));
        params.put("brandid", PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID, ""));
        params.put("goodsnum", code);
        params.put("timeStamp", System.currentTimeMillis() / 1000 + "");//加时间戳参数
        params.put("sign", MD5Util.md5(params));//md5加密并加参数
//        view.onLoading();
        RetrofitManager.getDefault().create(ApiServer.class).getGoodsData(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseListResult<GoodsInfo>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseListResult<GoodsInfo> baseResult) {
                        Trace.e("服务器回来数据 " + new Gson().toJson(baseResult));
                        if (baseResult.isSuccess()) {
                            view.getGoodsData(baseResult.getInfo().get(0));
                        } else {
                            view.onCommitError("提交失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.onCommitError("网络异常");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public void onDestroy() {
        cacheGoodsThread = null;
    }
}
